package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.constant.ChatMessageConstant;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.dto.chat.ConversationDto;
import com.example.everying.model.entity.chat.ChatConversationEntity;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.model.entity.system.SysNotification;
import com.example.everying.model.vo.chat.ChatMessageVo;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import com.example.everying.service.chat.impl.RedDotService;
import com.example.everying.service.system.SysNotificationService;
import com.example.everying.utils.StringUtils;
import com.example.everying.utils.AliGreenModerationUtil;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Component
public class SendMessageHandler implements MessageHandler {

    private static ChatConversationService chatConversationService;
    private static ChatMessagesService chatMessageService;
    private static AliGreenModerationUtil textModerationUtil;
    private static SysNotificationService sysNotificationService;
    private static RedDotService redDotService;

    @Autowired
    private void setService(
            ChatConversationService chatConversationService,
            ChatMessagesService chatMessageService
            , AliGreenModerationUtil textModerationUtil
            , SysNotificationService sysNotificationService,
            RedDotService redDotService
    ) {
        SendMessageHandler.chatConversationService = chatConversationService;
        SendMessageHandler.chatMessageService = chatMessageService;
        SendMessageHandler.textModerationUtil = textModerationUtil;
        SendMessageHandler.sysNotificationService = sysNotificationService;
        SendMessageHandler.redDotService = redDotService;
    }


    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
        String userId = WebSocketChatService.getUserId(session);
        String toUserId = message.getString("userId");
        String content = message.getString("content");
        String type = message.getString("messageType") == null ? "0" : message.getString("messageType");
        log.info("发送给{}的消息是{}", toUserId, content);
        // 校验用户ID合法性
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(toUserId)) {
            log.warn("用户ID为空");
            return;
        }
//        if (type.equals("0")) {
//            // 过滤违禁词
//            boolean isContainProhibitedWords = textModerationUtil.containsProhibitedWords(content);
//            if (isContainProhibitedWords) {
//                log.warn("包含违禁词");
//                return;
//            }
////                content = SensitiveWordReplaceV2Utils.replaceSensitiveWords(content, true);
//        }else if (type.equals("1")) {
//            boolean isProhibited = textModerationUtil.containsProhibitedContent(content);
//            if (isProhibited) {
//                log.warn("包含违规内容");
//                return;
//            }
//        }

        // 获取会话id
        ChatConversationEntity chatConversationEntity = chatConversationService.getConversation(userId, toUserId);
        ChatMessagesEntity entity = new ChatMessagesEntity();
        if (chatConversationEntity == null) {
            log.warn("会话不存在");
            return;
        }
        // 获取业务id
        entity.setBizId(getBizId(message, chatConversationEntity));

        // 保存消息
        entity.setConversationId(chatConversationEntity.getId());
        entity.setFormUserId(userId);
        entity.setToUserId(toUserId);
        entity.setPostMessages(content);
        entity.setMsgStatus(ChatMessageConstant.MESSAGE_STATUS_UNREAD); // 默认未读
        entity.setTime(LocalDateTime.now());
        entity.setMessagesType(ChatMessageConstant.MESSAGE_TYPE_ACTIVITY_CHAT);
        entity.setType(message.getString("messageType") == null ? "0" : message.getString("messageType")); // 默认为文本消息
        boolean isSave = chatMessageService.save(entity);
        if (!isSave) {
            log.error("保存消息失败，内容为: {}", content);
            return;
        }
        // 更新会话最后聊天id
        chatConversationService.updateLastMessageId(chatConversationEntity.getId(), entity.getId(), userId);
        // 构建响应JSON
        JSONObject resJson = buildResponseJson(userId, entity);
        JSONObject toResJson = buildResponseJson(toUserId, entity);


        // 给某个用户发消息
        WebSocketChatService.sendMessageToUserId(toUserId, toResJson.toJSONString());
        WebSocketChatService.sendMessageToUserId(userId, resJson.toJSONString());

        // 在重新发一个列表
        sendChatConversationList(userId);
        sendChatConversationList(toUserId);

        // 发送红点消息
        redDotService.sendRedDot(userId);
        redDotService.sendRedDot(toUserId);

    }

    private String getBizId(JSONObject message, ChatConversationEntity chatConversationEntity) {
        // 优先从message中获取bizId
        String bizId = message.containsKey("bizId") ? message.getString("bizId") : null;
        if (bizId != null) {
            return bizId;
        }
        // 如果message中没有且会话有最后消息ID
        if (chatConversationEntity.getLastMessageId() != null) {
            ChatMessagesEntity lastMessage = chatMessageService.getById(chatConversationEntity.getLastMessageId());

            // 安全处理lastMessage及其bizId
            if (lastMessage != null && lastMessage.getBizId() != null && !lastMessage.getBizId().isEmpty()) {
                bizId = lastMessage.getBizId();
            }
        }

        return bizId;
    }


    private JSONObject buildResponseJson(String userId, ChatMessagesEntity entity) {
        log.info("发送给{}的消息是{}", userId, entity);
        JSONObject resJson = new JSONObject();
        ChatMessageVo vo = chatMessageService.convertToDTO(entity);
        vo.setSender(entity.getFormUserId().equals(userId));
        resJson.put("type", "send");
        resJson.put("message", vo);
        resJson.put("conversationId", entity.getConversationId());
        return resJson;
    }

    @Async
    protected void sendChatConversationList(String userId) {
        List<ConversationDto> conversations = chatConversationService.getUserConversations(userId);
        JSONObject result = new JSONObject();
        result.put("type", "messageList");
        result.put("conversations", conversations);
        int unreadCount = Math.toIntExact(chatMessageService.count(new QueryWrapper<ChatMessagesEntity>().eq("to_user_id", userId).eq("msg_status", ChatMessageConstant.MESSAGE_STATUS_UNREAD)));
        int unreadCount2 = Math.toIntExact(sysNotificationService.count(new QueryWrapper<SysNotification>().eq("recipient_id", userId).eq("msg_status", "2")));
        result.put("unreadNum", unreadCount + unreadCount2);
        WebSocketChatService.sendMessageToUserId(userId, result.toJSONString());
    }

}
